<?php
set_include_path ( $_SERVER ['DOCUMENT_ROOT'] );
include_once 'admin/includes/functions/admin-functions.php';
global $CONFIG, $DBobject, $SMARTY;

$referer = parse_url($_SERVER['HTTP_REFERER']);
if($referer['host'] == $GLOBALS['HTTP_HOST'] && !empty($_SESSION['user']['admin']['id']) ){
	if (!empty($_POST['from']) && !empty($_POST['to'])) {
		$fromDate = date("Y-m-d", strtotime( str_replace('/', '-', $_POST['from'])));
		$toDate = date("Y-m-d", strtotime( str_replace('/', '-', $_POST['to'])));
		$payments = array();
		$sql = "SELECT tbl_payment.*, tbl_cart.*	
				FROM tbl_payment 
					LEFT JOIN tbl_cart ON payment_cart_id = cart_id  
					LEFT JOIN tbl_user ON payment_user_id = user_id  
		      LEFT JOIN tbl_order ON payment_id = order_payment_id 
				WHERE payment_status = 'A' 
					AND payment_deleted IS NULL
		      AND order_deleted IS NULL
					AND ( 
		    (DATE(order_modified) BETWEEN :from AND :to AND (payment_response_cardscheme = 'BankTransfer' OR payment_response_cardscheme = 'Bank Transfer') AND order_status_id = 4 )
		    OR (DATE(payment_created) BETWEEN :from AND :to AND (payment_response_cardscheme != 'BankTransfer' AND payment_response_cardscheme != 'Bank Transfer') )
		    )
				ORDER BY order_modified DESC";
		if($res = $DBobject->wrappedSql($sql, array(':from'=>$fromDate,':to'=>$toDate))){
			foreach ($res as $p){
				$sql = "SELECT * FROM tbl_cartitem WHERE cartitem_cart_id = :id AND cartitem_deleted IS NULL AND cartitem_cart_id <> '0' AND cartitem_product_id	 > 0 AND cartitem_class_flag = '0'";
				if($items = $DBobject->wrappedSql($sql,array(":id"=>$p['cart_id']))){
					
					$payments[$p['cart_id']] = $p;
					
					$sql = "SELECT * FROM tbl_address WHERE address_deleted IS NULL AND address_user_id = :user_id ORDER BY address_modified DESC LIMIT 1";
					if($address = $DBobject->wrappedSql($sql,array(":user_id"=>$p['payment_user_id']))) $payments[$p['cart_id']] = array_merge($p,$address[0]);
					
					foreach ($items as $c){
						$payments[$p['cart_id']]['cartitems'][$c['cartitem_id']] = $c;
						$sql = "SELECT * FROM tbl_cartitem_attr WHERE cartitem_attr_cartitem_id	= :id AND cartitem_attr_deleted IS NULL AND cartitem_attr_cartitem_id <> '0'";
			      $payments[$p['cart_id']]['cartitems'][$c['cartitem_id']]['attributes'] = $DBobject->wrappedSql($sql,array(":id"=>$c['cartitem_id'] ));
					}
				}			
			}
	    $SMARTY->assign('payments',$payments);
		}
		$COMP = json_encode($CONFIG->company);
		$SMARTY->assign('COMPANY', json_decode($COMP,TRUE));
		$SMARTY->display('labels.tpl');
	}
}
die();
